#include "buffer/page_allocator.h"

namespace boltDB {
Unorded_PageAllocator::Unorded_PageAllocator(uint16_t* pages_count, char* data)
    : free_page_count_(*pages_count) {
 
  auto page_ids_ = reinterpret_cast<page_id_t*>(data);
  next_page_id_ = page_ids_;
  free_pages_ = page_ids_ + 1;
}
page_id_t Unorded_PageAllocator::AllocatePage() {
  std::scoped_lock<std::mutex> locker(latch_);
  if (free_page_count_ != 0) {
    --free_page_count_;
    return *(free_pages_ + free_page_count_);
  }
  return (*next_page_id_)++;
}

bool Unorded_PageAllocator::DeallocatePage(page_id_t page_id) {
  std::scoped_lock<std::mutex> locker(latch_);
  if (MAX_FREE_PAGE_COUNT <= free_page_count_) {
    return false;
  }
  // 赋值给末尾元素
  *(free_pages_ + free_page_count_) = page_id;
  free_page_count_++;
  return true;
}

}  // namespace boltDB